package dev.android.yeqh.iask_sina.common;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.http.client.ClientProtocolException;
import org.htmlparser.NodeFilter;
import org.htmlparser.Parser;
import org.htmlparser.filters.HasAttributeFilter;
import org.htmlparser.filters.LinkRegexFilter;
import org.htmlparser.filters.NodeClassFilter;
import org.htmlparser.filters.OrFilter;
import org.htmlparser.filters.RegexFilter;
import org.htmlparser.filters.TagNameFilter;
import org.htmlparser.nodes.TagNode;
import org.htmlparser.nodes.TextNode;
import org.htmlparser.util.NodeList;
import org.htmlparser.util.ParserException;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;

import android.content.Context;
import android.widget.Toast;
import dev.android.yeqh.iask_sina.model.cidianItem;
import dev.android.yeqh.iask_sina.net.AccessWS;

public class Utils {
	public static Document getDocument(String result) throws SAXException, IOException, ParserConfigurationException {
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		DocumentBuilder builder = factory.newDocumentBuilder();
		InputStream is = new ByteArrayInputStream(result.getBytes("UTF-8"));
		return builder.parse(is);
	}
	
	public static List<String> getWords() throws ClientProtocolException, ParserConfigurationException, IOException, ParserException {
		List<String> ret = new ArrayList<String>();
		String start = "<div class=\"ctfl c6\">";
    	String end = "<div id=\"cont_right\">";
    	String result = AccessWS.getPage("http://cidian.iask.sina.com.cn/", start, end);
    	NodeFilter filter = new LinkRegexFilter("/search_cidian.php\\?key=.*");
    	
    	NodeList nl = new Parser(result).extractAllNodesThatMatch(filter);
    	for (int i = 0; i < nl.size(); i++) {
    		ret.add(nl.elementAt(i).getFirstChild().getText());
    	}
    	
    	return ret;
	}
	
	public static List<cidianItem> searchCidian(String keyword, int page) throws ClientProtocolException, ParserConfigurationException, IOException, ParserException {
		List<cidianItem> ret = new ArrayList<cidianItem>();
    	String result = AccessWS.getPage("http://cidian.iask.sina.com.cn/search_cidian.php?key=" + URLEncoder.encode(keyword, "GB2312") + "&page=" + page);
    	NodeFilter left = new HasAttributeFilter("class", "result_list");
    	NodeFilter right = new HasAttributeFilter("class", "pic_text");
    	NodeFilter filter = new OrFilter(left, right);
    	NodeFilter titleFilter = new TagNameFilter("h3");
    	NodeFilter summaryFilter = new TagNameFilter("p");
    	NodeFilter dateFilter = new RegexFilter(".*：[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}$");
    	NodeFilter textFilter = new NodeClassFilter(TextNode.class);
    	
    	Parser parser = new Parser(result);
    	NodeList nl = parser.extractAllNodesThatMatch(filter);
    	String title = "";
    	String summary = "";
    	String upTime = "";
    	NodeList tmpNL = null;
    	for (int i = 0; i < nl.size(); i++) {
    		title = "";
        	summary = "";
        	
    		cidianItem item = new cidianItem();
    		NodeList nl2 = nl.elementAt(i).getChildren();
    		
    		//extract title
    		parser.setInputHTML(nl2.extractAllNodesThatMatch(titleFilter).toHtml());
    		tmpNL = parser.extractAllNodesThatMatch(textFilter);
    		for(int j = 0; j < tmpNL.size(); j++) {
    			title += tmpNL.elementAt(j).getText();
    		}
    		item.setTitle(title);
    		
    		//extract summary
    		parser.setInputHTML(nl2.extractAllNodesThatMatch(summaryFilter).toHtml());
    		tmpNL = parser.extractAllNodesThatMatch(textFilter);
    		for(int j = 0; j < tmpNL.size(); j++) {
    			summary += tmpNL.elementAt(j).getText();
    		}
    		item.setSummary(summary);
    		
    		//extract update time
    		parser.setResource(nl2.toHtml());
    		upTime = parser.extractAllNodesThatMatch(dateFilter).elementAt(0).getText();
    		item.setDate(upTime);
    		
    		ret.add(item);
    	}
    	
    	return ret;
	}
	
	public static List<String> getItemDetail(String title) throws ClientProtocolException, ParserConfigurationException, IOException, ParserException {
		List<String> ret = new ArrayList<String>();
    	String result = AccessWS.getPage("http://cidian.iask.sina.com.cn/article_browse.php?title=" + URLEncoder.encode(title, "GB2312"));
    	NodeFilter filter = new HasAttributeFilter("class", "summary");
    	NodeFilter textFilter = new NodeClassFilter(TextNode.class);
    	NodeFilter brFilter = new TagNameFilter("br");
    	NodeFilter orFilter = new OrFilter(textFilter, brFilter);
    	
    	Parser parser = new Parser(result);
    	NodeList nl = parser.extractAllNodesThatMatch(filter);
    	String summary = "";
    	NodeList tmpNL = null;
    	for (int i = 0; i < nl.size(); i++) {
        	summary = "";
    		
    		//extract summary
    		parser.setInputHTML(nl.elementAt(i).toHtml());
    		tmpNL = parser.extractAllNodesThatMatch(orFilter);
    		for(int j = 0; j < tmpNL.size(); j++) {
    			if (tmpNL.elementAt(j) instanceof TagNode) {
    				summary += "\n";
    				continue;
    			}
    			if (tmpNL.elementAt(j).getText().equals("编辑此段") || tmpNL.elementAt(j).getText().trim().length() == 0) {
    				continue;
    			}
    			summary += tmpNL.elementAt(j).getText() + "\n";
    		}
    		
    		ret.add(summary);
    	}
    	
    	return ret;
	}
	
	public static void showMessage(Context context, String msg) {
		Toast.makeText(context, msg, 1000).show();
	}
	
	public static boolean empty(String str) {
		if (str == null || "".equals(str.trim())) {
			return true;
		} else {
			return false;
		}
	}
	
	public static void showMessage(Context context, Exception e) {
		Toast.makeText(context, e.toString(), 1000).show();
		e.printStackTrace();
	}
}
